//
//  GGTUserViewController.m
//  GGT
//
//  Created by 安静的美男子 on 14/10/27.
//  Copyright (c) 2014年 GGT. All rights reserved.
//

#import "GGTUserViewController.h"
#import "GGTUserTableViewCell.h"
#import "GGTAppDelegate.h"
#import "SBJson.h"
#import "GGTWBUsersShowModel.h"
#import "UIImageView+WebCache.h"
#import "GGTWeiBoDetailViewController.h"
#import "GGTMyFavoriteViewController.h"
#import "GGTOurViewController.h"
@interface GGTUserViewController ()<UITableViewDataSource, UITableViewDelegate,WBHttpRequestDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
//页面tableView
@property (nonatomic, retain) UITableView *userTableView;
//存放数据用数组
@property (nonatomic, retain) NSMutableArray *myArr;
@property (nonatomic, retain) NSMutableArray *setUpArr;
@property (nonatomic, retain) NSMutableArray *mapArr;
@property (nonatomic, retain) NSMutableArray *weiboArr;
//页面上方数据
@property (nonatomic, retain) GGTWBUsersShowModel *receiveModel;
@property (nonatomic, retain) UIImageView *userPhotoImageView;
@property (nonatomic, retain) UILabel *userNameLabel;//名字
@property (nonatomic, retain) UILabel *userLocationLabel;//居住城市
@property (nonatomic, retain) UILabel *userDescriptionLabel;//用户个性签名
//缓存大小
@property (nonatomic, assign) float cachSize;
@end

@implementation GGTUserViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.weiboArr = [NSMutableArray arrayWithObjects:@"我的微博", nil];
        self.myArr = [NSMutableArray arrayWithObjects:@"我的收藏", nil];
        self.setUpArr = [NSMutableArray arrayWithObjects:@"清除缓存", @"关于我们", nil];
        self.mapArr = [NSMutableArray arrayWithObjects:@"地图设置", nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //关于导航栏上登陆按钮
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:[NSString stringWithFormat:@"登陆"] style:UIBarButtonItemStylePlain target:self action:@selector(loadingButtonClicked:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    //判断登陆状态
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"userID"]!= nil) {
        self.navigationItem.rightBarButtonItem.title = @"注销";
    }
    //主页面
    self.userTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height / 5 * 2, self.view.frame.size.width, self.view.frame.size.height / 5 * 3) ];
    self.userTableView.dataSource = self;
    self.userTableView.delegate = self;
    [self.view addSubview:self.userTableView];
    //用户背景
    UIImageView *lable = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/5 * 2 + 68)];
    lable.image = [UIImage imageNamed:@"userBack.jpg"];
    [self.view addSubview:lable];
    
    self.userPhotoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(lable.frame.size.width / 6 * 2,lable.frame.size.height / 3,lable.frame.size.width / 6 * 2,lable.frame.size.height / 3)];
//    self.userPhotoImageView.image = [UIImage imageNamed:@"酒店.png"];
    [lable addSubview:self.userPhotoImageView];
    
    self.userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(lable.frame.size.width / 6 * 1, lable.frame.size.height / 3 * 2 + 10, lable.frame.size.width / 6 * 2, 40)];
    self.userNameLabel.text = @"";
    [lable addSubview:self.userNameLabel];
    
    self.userLocationLabel = [[UILabel alloc]initWithFrame:CGRectMake(lable.frame.size.width / 6 * 4, lable.frame.size.height / 3 * 2 + 10, lable.frame.size.width / 2, 40)];
    self.userLocationLabel.text = @"";
    [lable addSubview:self.userLocationLabel];
    
    self.userDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(lable.frame.size.width/ 6  , lable.frame.size.height / 3 * 2 + 30, lable.frame.size.width/ 6 * 4, 80 )];
    self.userDescriptionLabel.text = @"请登录";
    self.userDescriptionLabel.numberOfLines = 0;
    [lable addSubview:self.userDescriptionLabel];
    //用户登录
    [self userLoading];
    //注册通知中心
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self selector:@selector(userLoading) name:@"userLoading" object:nil];
    [notiCenter addObserver:self selector:@selector(loadButtonTitle) name:@"loadButtonTitle" object:nil];
}
//获取用户信息
- (void)userLoading
{
    //获取用户信息
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] != nil && [[NSUserDefaults standardUserDefaults]objectForKey:@"UserAccessToken"]!= nil)
    {
        NSDictionary *params = @{@"uid": [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"]};
        [WBHttpRequest requestWithAccessToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"UserAccessToken"] url:@"https://api.weibo.com/2/users/show.json" httpMethod:@"GET" params:params delegate:self withTag:@"1111"];
    }
}
- (void)loadButtonTitle
{
    self.navigationItem.rightBarButtonItem.title = @"登陆";
}
//点击登陆按钮状态
- (void)loadingButtonClicked:(UIBarButtonItem *)button
{
    
    if ([button.title  isEqual: @"登陆"]) {
        
        WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        request.redirectURI = @"http://blog.csdn.net/qq11231325";
        request.scope = @"all";
        request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                             @"Other_Info_1": [NSNumber numberWithInt:123],
                             @"Other_Info_2": @[@"obj1", @"obj2"],
                             @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
        [WeiboSDK sendRequest:request];
        button.title = @"注销";
    } else {
        [WeiboSDK logOutWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"UserAccessToken"] delegate:self withTag:@"user1"];
        

    }
}
/**
 收到一个来自微博Http请求的响应
 
 @param response 具体的响应对象
 */
- (void)request:(WBHttpRequest *)request didReceiveResponse:(NSURLResponse *)response
{
    
}

/**
 收到一个来自微博Http请求失败的响应
 
 @param error 错误信息
 */

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error
{

}

/**
 收到一个来自微博Http请求的网络返回
 
 @param result 请求返回结果
 */

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    if ([result isEqualToString:@"{\"result\":\"true\"}"]) {
        self.navigationItem.rightBarButtonItem.title =@"登陆";
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"userID"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"UserAccessToken"];
        self.userDescriptionLabel.text = @"请登陆";
    }

}


/**
 收到一个来自微博Http请求的网络返回
 
 @param data 请求返回结果
 */
#pragma mark - 豆瓣解析相关回调
- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data
{
	SBJsonParser *parser = [[SBJsonParser alloc] init];
    id result = [parser objectWithData:data];
    self.receiveModel = [[GGTWBUsersShowModel alloc]initWithDictionary:result];
    
    self.userNameLabel.text = self.receiveModel.name;
    self.userLocationLabel.text = self.receiveModel.location;
    self.userDescriptionLabel.text = self.receiveModel.description111;
    [self.userPhotoImageView setImageWithURL:[NSURL URLWithString:self.receiveModel.avatar_large]];
    
}
#pragma mark - tableView相关回调

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    switch (section) {
        case 0:
            return self.weiboArr.count;
            break;
        case 1:
            return self.myArr.count;
            break;
        case 2:
            return self.mapArr.count;
            break;
        default:
            return self.setUpArr.count;
            break;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 10;
    } else {
    return 20.0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"0"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"0"]autorelease];
        }
        cell.textLabel.text = self.weiboArr[indexPath.row];

        return cell;
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"1"]autorelease];
        }
        cell.textLabel.text = self.myArr [indexPath.row];
        return cell;
    } else if (indexPath.section == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"2"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"2"];
        }
        cell.textLabel.text = self.mapArr [indexPath.row];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"3"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"3"];
        }
        cell.textLabel.text = self.setUpArr [indexPath.row];
        return cell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] != nil) {
        if (indexPath.section == 0) {
            GGTWeiBoDetailViewController *weiboVC = [[GGTWeiBoDetailViewController alloc]init];
            [self.navigationController pushViewController:weiboVC animated:YES];
            [weiboVC release];
        }
        if (indexPath.section == 1) {
            GGTMyFavoriteViewController * myFavoriteViewVC = [[GGTMyFavoriteViewController alloc]init];
            [self.navigationController pushViewController:myFavoriteViewVC animated:YES];
            [myFavoriteViewVC release];
        } else if (indexPath.section == 2) {
            UIActionSheet *act = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"标准模式" otherButtonTitles:@"卫星模式", @"混合模式", nil];
            [act showInView:self.view];
        } else if (indexPath.section == 3) {
            if (indexPath.row == 1) {
                GGTOurViewController *our = [[GGTOurViewController alloc]init];
                [self.navigationController pushViewController:our animated:YES];
                [our release];
            }
        }
     } else {
         if (indexPath.section != 3) {
             UIAlertView *aler = [[UIAlertView alloc]initWithTitle:nil message:@"请登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
             [aler show];
         }
     }
     if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            //
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               NSLog(@"files :%lu",(unsigned long)[files count]);
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               
                           });
            NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
            [notiCenter postNotificationName:@"缓存" object:[NSString stringWithFormat:@"%.1fM", self.cachSize] userInfo:nil];
            //
            UIAlertView *myTip = [[UIAlertView alloc]initWithTitle:nil message:@"缓存已经清理成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [myTip show];
        }
    }

}
// 通常用于删除缓存的时，计算缓存大小
// 单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"mapType"];
    } else if (buttonIndex == 1)
    {
        [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"mapType"];
    } else if (buttonIndex == 2){
        [[NSUserDefaults standardUserDefaults]setObject:@"2" forKey:@"mapType"];
    } else {
        
    }

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"mapType" object:nil userInfo:nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [_setUpArr release];
    [_mapArr release];
    [super dealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
